package com.course.coursedesign2022.service;

import com.course.coursedesign2022.mapper.UserMapper;
import com.course.coursedesign2022.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class Login {
    @Autowired
    UserMapper userMapper;

    public  UserInfo login(int id){
        //读取数据
        UserInfo userInfoById = userMapper.getUserInfoById(id);
        Date lastLogin = userInfoById.getLastLogin();
        Date date = new Date();
        Integer growscore = userInfoById.getGrowscore();
        Integer scoretotal = userInfoById.getScoretotal();
        //判断是否同一天
        int year = date.getYear();
        int month = date.getMonth();
        int day = date.getDay();

        if (userInfoById.getTodayIsLogin() == 1){
            System.out.println("今日已经登录过");
        }

            userInfoById.setThisLogin(date);
        //如果当前年月日与上次登录的年月日不同，则表示不是同一天
        if (lastLogin == null
                ||year != lastLogin.getYear()
            || month != lastLogin.getMonth()
            || day != lastLogin.getDay()
            ){
            //修改上次登陆时间和本次登陆时间
            userInfoById.setLastLogin(date);
            //设置今日已登录
            userInfoById.setTodayIsLogin(1);
            //加分
            userInfoById.setGrowscore(growscore + 1);
            userInfoById.setScoretotal(scoretotal + 1);
            System.out.println("欢迎登录，获取1成长积分");
        }
        System.out.println("成长积分为："+ userInfoById.getGrowscore());
        System.out.println("可交换积分为："+ userInfoById.getExchangescore());
        System.out.println("总积分为："+ userInfoById.getScoretotal());


        //写回数据库
        userMapper.updateUserInfo(userInfoById);
        return userInfoById;
    }
}
